package com.hzvdvmc.autosale;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.hzvdvmc.autosale.common.CrashHandler;
import com.hzvdvmc.autosale.constant.SpKey;
import com.hzvdvmc.autosale.constant.TimeConstant;
import com.hzvdvmc.autosale.sale.MainActivity;
import com.hzvdvmc.autosale.util.LogToFileHelper;
import com.hzvdvmc.autosale.util.LogUtil;
import com.hzvdvmc.autosale.util.SPUtils;
import com.hzvdvmc.autosale.util.Utils;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android_serialport_api.SeriaPortClient;
import android_serialport_api.SerialPort;
import android_serialport_api.SerialPortFinder;

/**
 * Created by william on 2017/11/8.
 */

public class MyApp extends Application {

    private List<Activity> activityList = new ArrayList<>();

    public static HashMap<String, SeriaPortClient> portMap = new HashMap<>();
    public static List<String> seriList = new ArrayList<>();

    public static boolean isHeart = true;

    @Override
    public void onCreate() {
        super.onCreate();
        CrashHandler.getInstance().init(this);
        ZXingLibrary.initDisplayOpinion(this);
        Utils.init(this);
        LogToFileHelper.init(this);

        try {

            SerialPortFinder finder = new SerialPortFinder();
            String[] allDevices = finder.getAllDevicesPath();
            for (String str : allDevices) {
                if (new File(str).exists()) {
                    seriList.add(str);
                }
            }
            LogUtil.i("serialport", "Connected devicesName:" + seriList.toString());

//            String devA = SPUtils.getInstance().getString(SpKey.SERIAL_A,SeriaPortClient.DEV_A);
//            String devB = SPUtils.getInstance().getString(SpKey.SERIAL_B,SeriaPortClient.DEV_B);
//            String devC = SPUtils.getInstance().getString(SpKey.SERIAL_C,SeriaPortClient.DEV_B);
//            String devD = SPUtils.getInstance().getString(SpKey.SERIAL_D,SeriaPortClient.DEV_B);
//            SeriaPortClient.DEV_A = devA;
//            SeriaPortClient.DEV_B = devB;
//            SeriaPortClient.DEV_C = devC;
//            SeriaPortClient.DEV_D = devD;
//            portMap.put("A", new SeriaPortClient(devA));
//            portMap.put("B", new SeriaPortClient(devB));
//            portMap.put("C", new SeriaPortClient(devC));
//            portMap.put("D", new SeriaPortClient(devD));

            portMap.put("A", new SeriaPortClient(SeriaPortClient.DEV_A));
            portMap.put("B", new SeriaPortClient(SeriaPortClient.DEV_B));
            portMap.put("C", new SeriaPortClient(SeriaPortClient.DEV_C));
            portMap.put("D", new SeriaPortClient(SeriaPortClient.DEV_D));


        } catch (Exception e) {
            e.printStackTrace();
        }

        initTimeSetData();


    }


    private void initTimeSetData() {
        //第一次进来记得初始化
        String timeWait = SPUtils.getInstance().getString(SpKey.TIME_WAIT);
        if (TextUtils.isEmpty(timeWait)) {
            SPUtils.getInstance().put(SpKey.TIME_ADVER, TimeConstant.TIME_OUT_ADVER);
            SPUtils.getInstance().put(SpKey.TIME_PAY, TimeConstant.TIME_OUT_PAY);
            SPUtils.getInstance().put(SpKey.TIME_WAIT, TimeConstant.TIME_OUT_WAIT);
        }
    }

    private void closeSerialPort() {
        for (SeriaPortClient client : portMap.values()) {
            client.close();
        }
    }
    // ------------------------------activity管理-----------------------//

    // activity管理：从列表中移除activity
    public void removeActivity(Activity activity) {
        if (activityList.contains(activity)) {
            activityList.remove(activity);
            if (activity != null) {
                activity.finish(); // 销毁当前Activity
            }
        }
    }

    // activity管理：添加activity到列表
    public void addActivity(Activity activity) {
        activityList.add(activity);
    }

    // activity管理：结束所有activity
    public void finishAllActivity() {
        for (Activity activity : activityList) {
            if (null != activity) {
                activity.finish();
            }
        }
    }

    public void restartApp() {
        Intent intent = new Intent(this, MainActivity.class);
        // 参数1：包名，参数2：程序入口的activity
        PendingIntent restartIntent = PendingIntent.getActivity(this, 0,
                intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + TimeConstant.RESTART,
                restartIntent);
        exitApp();
    }

    /**
     * 退出程序，之前要把所有的Activity干掉,关掉串口
     */
    public void exitApp() {
        closeSerialPort();
        finishAllActivity();
        killMyAPP();
    }

    private void killMyAPP() {
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    public static void startSerialHeart() throws NullPointerException {
        if (portMap != null) {
            portMap.get("A").startHeartBeat();
            portMap.get("B").startHeartBeat();
            portMap.get("C").startHeartBeat();
            portMap.get("D").startHeartBeat();
            isHeart = true;
        }
    }


    public static void stopSerialHeart() throws NullPointerException {
        if (portMap != null) {
            portMap.get("A").stopHeartBeat();
            portMap.get("B").stopHeartBeat();
            portMap.get("C").stopHeartBeat();
            portMap.get("D").stopHeartBeat();
            isHeart = false;
        }
    }

}

